package com.ccut.xunfeiSpringboot.service.impl;

import com.ccut.xunfeiSpringboot.common.AvatarConfig;
import com.ccut.xunfeiSpringboot.service.AvatarService;
import com.ccut.xunfeiSpringboot.utils.AuthUtil;
import com.ccut.xunfeiSpringboot.utils.AvatarWsUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

@Slf4j
@Service
public class AvatarServiceImpl implements AvatarService {

    private final AvatarConfig.AvatarProperties properties;
    private AvatarWsUtil avatarWsUtil;
    private Timer heartbeatTimer;
    private String receivedMessage; // 存储接收到的消息
    private String currentVcn; // 存储当前轮次的声音配置

    public AvatarServiceImpl(AvatarConfig.AvatarProperties properties) {
        this.properties = properties;
    }

    @Override
    public void startSession(int round) throws Exception {
        // 根据轮次设置当前声音
        switch (round) {
            case 1: currentVcn = properties.vcn(); break;
            case 2: currentVcn = properties.vcn2(); break;
            case 3: currentVcn = properties.vcn3(); break;
            case 4: currentVcn = properties.vcn4(); break; // 新增第4轮配置
            default: currentVcn = properties.vcn();
        }

        String requestUrl = AuthUtil.assembleRequestUrl(
                properties.avatarUrl(),
                properties.apiKey(),
                properties.apiSecret()
        );

        this.avatarWsUtil = new AvatarWsUtil(requestUrl);

        // 设置消息回调 - 只存储 stream_info 类型的消息
        avatarWsUtil.setMessageCallback(message -> {
            try {
                JSONObject json = JSONObject.parseObject(message);
                JSONObject payload = json.getJSONObject("payload");
                if (payload != null) {
                    JSONObject avatar = payload.getJSONObject("avatar");
                    if (avatar != null && "stream_info".equals(avatar.getString("event_type"))) {
                        this.receivedMessage = message;
                        log.info("Received stream_info message: {}", message);
                    }
                }
            } catch (Exception e) {
                log.error("Error processing message: {}", e.getMessage());
            }
        });

        CountDownLatch startLatch = new CountDownLatch(1);
        avatarWsUtil.start(buildStartRequest(round, currentVcn), startLatch);
        startLatch.await();

        startHeartbeat();
    }

    @Override
    public String getReceivedMessage() {
        return this.receivedMessage;
    }

    @Override
    @Async
    public void sendText(String text) {
        try {
            JSONObject textRequest = buildTextRequest(text);
            avatarWsUtil.send(textRequest);
        } catch (Exception e) {
            log.error("Error sending text: {}", e.getMessage(), e);
        }
    }

    @Override
    @Async
    public void sendAudio(byte[] audioData) {
        try {
            String requestId = UUID.randomUUID().toString();
            int status = 0;
            String audioBase64 = java.util.Base64.getEncoder().encodeToString(audioData);
            JSONObject audioRequest = buildAudioRequest(requestId, status, audioBase64);
            avatarWsUtil.send(audioRequest);
        } catch (Exception e) {
            log.error("Error sending audio: {}", e.getMessage(), e);
        }
    }

    @Override
    public void stopSession() {
        if (avatarWsUtil != null) {
            avatarWsUtil.close();
        }
        if (heartbeatTimer != null) {
            heartbeatTimer.cancel();
        }
    }

//    private JSONObject buildStartRequest(int round, String vcn) {
//        // 根据轮次选择不同的 avatarId
//        String avatarId;
//        switch (round) {
//            case 1: avatarId = properties.avatarId(); break;
//            case 2: avatarId = properties.avatarId2(); break;
//            case 3: avatarId = properties.avatarId3(); break;
//            case 4: avatarId = properties.avatarId4(); break; // 新增第4轮配置
//            default: avatarId = properties.avatarId();
//        }
//
//        log.info("Starting session for round {} with avatarId: {}, vcn: {}", round, avatarId, vcn);
//
//        JSONObject header = new JSONObject()
//                .fluentPut("app_id", properties.appId())
//                .fluentPut("ctrl", "start")
//                .fluentPut("request_id", UUID.randomUUID().toString())
//                .fluentPut("scene_id", "77213753883627520");
//
//        JSONObject parameter = new JSONObject()
//                .fluentPut("avatar", new JSONObject()
//                        .fluentPut("avatar_id", avatarId)
//                        .fluentPut("width", 720)
//                        .fluentPut("height", 1280)
//                        .fluentPut("stream", new JSONObject()
//                                .fluentPut("protocol", "xrtc")
//                                .fluentPut("fps", 25)
//                                .fluentPut("bitrate", 5000)
//                                .fluentPut("alpha", 0)))
//                .fluentPut("tts", new JSONObject()
//                        .fluentPut("speed", 50)
//                        .fluentPut("vcn", vcn)); // 使用传入的vcn
//
//        return new JSONObject()
//                .fluentPut("header", header)
//                .fluentPut("parameter", parameter);
//
//        JSONObject payload = new JSONObject()
//                .fluentPut("background", new JSONObject()
//                        .fluentPut("data", '22SLM2teIw+aqR6Xsm2JbH6Ng310kDam2NiCY/RQ9n6s3nYJXloZWW1l64/g32vrn7d2lJQR7m9xD5EHYkVs145208ZzlALed5fXJBLgLg4tI+ItIrPB8y67oDnM0DlUnSbMKSZ2DnxdLF3ddbWYUNtAx2/SVhCs4ulm5khUJcH5ZE0N6JFb1MGDhwpFJx8sIPCRz4dxIqFDWC6Sntu2rDq7lyU/9tyCb9m2mFSr3nlqGBQ0nKFVF4MdjbbZH74dOpQ1lYZ0apoX4ae1Q9TYZnW9U7n+WWWxGep39VF73qLYIsTRdGv8QSe7aEB6s1XQQP19PdnMEVkH6f5ap5c00CKQfe8h05CHKHvsnQ3IB5A='));
//        return new JSONObject()
//                .fluentPut("header", header)
//                .fluentPut("parameter", parameter)
//                .fluentPut("payload", payload);
//    }


    private JSONObject buildStartRequest(int round, String vcn) {
        // 根据轮次选择不同的 avatarId
        String avatarId;
        switch (round) {
            case 1: avatarId = properties.avatarId(); break;
            case 2: avatarId = properties.avatarId2(); break;
            case 3: avatarId = properties.avatarId3(); break;
            case 4: avatarId = properties.avatarId4(); break; // 新增第4轮配置
            default: avatarId = properties.avatarId();
        }

        log.info("Starting session for round {} with avatarId: {}, vcn: {}", round, avatarId, vcn);

        JSONObject header = new JSONObject()
                .fluentPut("app_id", properties.appId())
                .fluentPut("ctrl", "start")
                .fluentPut("request_id", UUID.randomUUID().toString())
                .fluentPut("scene_id", "77213753883627520");

        JSONObject parameter = new JSONObject()
                .fluentPut("avatar", new JSONObject()
                        .fluentPut("avatar_id", avatarId)
                        .fluentPut("width", 720)
                        .fluentPut("height", 1280)
                        .fluentPut("stream", new JSONObject()
                                .fluentPut("protocol", "xrtc")
                                .fluentPut("fps", 25)
                                .fluentPut("bitrate", 5000)
                                .fluentPut("alpha", 0)))
                .fluentPut("tts", new JSONObject()
                        .fluentPut("speed", 50)
                        .fluentPut("vcn", vcn)); // 使用传入的vcn

        JSONObject payload = new JSONObject()
                .fluentPut("background", new JSONObject()
                        .fluentPut("data", "22SLM2teIw+aqR6Xsm2JbH6Ng310kDam2NiCY/RQ9n6s3nYJXloZWW1l64/g32vrn7d2lJQR7m9xD5EHYkVs145208ZzlALed5fXJBLgLg4tI+ItIrPB8y67oDnM0DlUnSbMKSZ2DnxdLF3ddbWYUNtAx2/SVhCs4ulm5khUJcH5ZE0N6JFb1MGDhwpFJx8sIPCRz4dxIqFDWC6Sntu2rFWtHvCyUP5ld0pSvdXTqt1/5YAlGOPZ03TlLQUzhElrQDzUZmTMXe7EoQbdsKvyeoq4Ch8lJ6HzhISzajMoHtRcc3qdSUiTWUYDWg16LZZbavZqUuA0sQv6G5j0DZCooIgo/uDW0gne2ahM/qAdzfw="));

        return new JSONObject()
                .fluentPut("header", header)
                .fluentPut("parameter", parameter)
                .fluentPut("payload", payload);
    }

    private JSONObject buildTextRequest(String text) {
        JSONObject header = new JSONObject()
                .fluentPut("app_id", properties.appId())
                .fluentPut("ctrl", "text_driver")
                .fluentPut("request_id", UUID.randomUUID().toString());

        JSONObject parameter = new JSONObject()
                .fluentPut("tts", new JSONObject()
                        .fluentPut("vcn", currentVcn) // 使用当前轮次的vcn
                        .fluentPut("speed", 50));

        JSONObject payload = new JSONObject()
                .fluentPut("text", new JSONObject()
                        .fluentPut("content", text));

        return new JSONObject()
                .fluentPut("header", header)
                .fluentPut("parameter", parameter)
                .fluentPut("payload", payload);
    }

    private JSONObject buildAudioRequest(String requestId, int status, String content) {
        JSONObject header = new JSONObject()
                .fluentPut("app_id", properties.appId())
                .fluentPut("ctrl", "audio_driver")
                .fluentPut("request_id", requestId);

        JSONObject payload = new JSONObject()
                .fluentPut("audio", new JSONObject()
                        .fluentPut("status", status)
                        .fluentPut("audio", content));

        return new JSONObject()
                .fluentPut("header", header)
                .fluentPut("payload", payload);
    }

    private void startHeartbeat() {
        heartbeatTimer = new Timer();
        heartbeatTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (avatarWsUtil != null) {
                    avatarWsUtil.send(buildPingRequest());
                }
            }
        }, 0, 5000);
    }

    private JSONObject buildPingRequest() {
        JSONObject header = new JSONObject()
                .fluentPut("app_id", properties.appId())
                .fluentPut("ctrl", "ping")
                .fluentPut("request_id", UUID.randomUUID().toString());
        return new JSONObject().fluentPut("header", header);
    }
}